<template>
  <div class="forgot-password-container">
    <el-card class="forgot-password-card">
      <div class="forgot-password-title">找回密码</div>
      <el-form ref="forgotPasswordForm" :model="forgotPasswordForm" :rules="forgotPasswordRules" class="forgot-password-form">
        <el-form-item prop="email">
          <el-input v-model="forgotPasswordForm.email" placeholder="请输入邮箱" prefix-icon="Message" @input="handleInput('email', $event)" />
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="forgotPasswordForm.code" placeholder="请输入验证码" prefix-icon="Message" @input="handleInput('code', $event)">
            <template #suffix>
              <el-button type="text" @click="getCode" :disabled="countDown > 0">{{ countDown > 0 ? `${countDown}秒后重新获取` : '获取验证码' }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input v-model="forgotPasswordForm.newPassword" type="password" placeholder="请输入新密码" prefix-icon="Lock" @input="handleInput('newPassword', $event)" />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input v-model="forgotPasswordForm.confirmPassword" type="password" placeholder="请确认新密码" prefix-icon="Lock" @input="handleInput('confirmPassword', $event)" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="forgot-password-btn" @click="handleForgotPassword">重置密码</el-button>
        </el-form-item>
        <div class="login-link">
          想起密码了? <el-link type="primary" :underline="false" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

// 添加输入处理函数，确保输入值立即更新
const handleInput = (field, value) => {
  console.log(`更新${field}:`, value);
  forgotPasswordForm[field] = value;
};

import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import request from '../utils/request';

const router = useRouter();
const countDown = ref(0);

const forgotPasswordForm = reactive({
    email: '',
    code: '',
    newPassword: '',
    confirmPassword: ''
  });

const forgotPasswordRules = {
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { pattern: /^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value !== forgotPasswordForm.newPassword) {
        callback(new Error('两次密码输入不一致'));
      } else {
        callback();
      }
    }, trigger: 'blur' }
  ]
};

const handleForgotPassword = async () => {
    try {
      const email = forgotPasswordForm.email;
      const code = forgotPasswordForm.code;
      const newPassword = forgotPasswordForm.newPassword;
      const response = await request.post('/user/findPassword', { email, code, newPassword });
      if (response.code === 200) {
        ElMessage.success('密码重置成功，请登录');
        router.push('/login');
      } else {
        ElMessage.error(response.message || '密码重置失败');
      }
    } catch (error) {
      ElMessage.error('密码重置失败，请重试');
    }
  };

const getCode = () => {
    const email = forgotPasswordForm.email;
    if (!email || !/^[0-9a-zA-Z_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email)) {
      ElMessage.warning('请输入正确的邮箱');
      return;
    }

    // 实际调用发送验证码接口
    request.post('/user/sendCode', { email }).then(res => {
      if (res.code === 200) {
        ElMessage.success('验证码发送成功，请注意查收');
        countDown.value = 60;
        const timer = setInterval(() => {
          countDown.value--;
          if (countDown.value <= 0) {
            clearInterval(timer);
          }
        }, 1000);
      } else {
        ElMessage.error(res.message || '验证码发送失败');
      }
    }).catch(error => {
      ElMessage.error('验证码发送失败，请重试');
    });
  };

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.forgot-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.forgot-password-card {
  width: 400px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  overflow: hidden;
}

.forgot-password-title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin: 20px 0;
  color: #303133;
}

.forgot-password-form {
  padding: 20px;
}

.forgot-password-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-link {
  text-align: center;
  margin-top: 15px;
  color: #606266;
}
</style>